from messageHandler import MessageHandler
from udpSocket import UDPsocket
from api import API
import threading
import logging
import json
import sys

class Listener(threading.Thread):
    
    __udpSocket = None
    hostname = None
    
    def run(self):
        try:
            logging.info('Starting LinRemote server...')
            self.__udpSocket = UDPsocket()
            self.hostname = self.__udpSocket.hostname
        except Exception as msg:
            logging.error('Unable to start server. Error code: ' + str(msg))
            sys.exit()
        logging.info('LinRemote server started.')
        self.looper()
        
    def looper(self):
        while True:
            data, addr = self.__udpSocket.receivedMessage()
            if MessageHandler().checkData(data, addr):
                try:
                    data = json.loads(str(data, 'utf-8'))
                except Exception:
                    data = MessageHandler().crypted(data, addr)
                    data = json.loads(str(data, 'utf-8'))
                self.execute(data, addr)
            else:
                response = {}
                response.update({'active':'false'})
                self.__udpSocket.sendMessage(response, addr, True)
                logging.debug("Received data validation returned 'False'.")
                
    def execute(self, data, addr):
        try:
            try:
                getattr(API(), data['function'])(self.__udpSocket, addr, *data['args'])
            except KeyError:
                getattr(API(), data['function'])(self.__udpSocket, addr)
        except Exception as msg:
            logging.error('Execution of ' + data['function'] + ' failed. Error Code: ' + str(msg))